package com.maigao.core.login.handler;

import com.maigao.core.exception.BaseException;
import com.maigao.core.exception.ServerCode;
import com.maigao.core.login.annotation.ThirdLoginHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author awei
 * @description:
 * @date 2022/5/19 10:24 下午
 */
@Slf4j
@Component
@SuppressWarnings("rawtypes")
public class LoginHandlerFactory implements ApplicationContextAware {
    private Container container = new Container();

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, IThirdLoginHandler> map = applicationContext.getBeansOfType(IThirdLoginHandler.class);
        for (IThirdLoginHandler bean : map.values()) {
            ThirdLoginHandler thirdLoginHandler = bean.getClass().getAnnotation(ThirdLoginHandler.class);
            if (Objects.isNull(thirdLoginHandler) || StringUtils.isEmpty(thirdLoginHandler.value())) {
                log.warn("bean:{},has not Annotation @ThirdLoginHandler", bean.getClass());
                throw new BaseException(ServerCode.NOT_LOGIN);
            }
            container.put(thirdLoginHandler.value(), bean);
        }
    }

    /**
     * 业务对象容器类
     */
    private static class Container {
        private final Map<String, IThirdLoginHandler> beanMap = new HashMap<>();

        /**
         * 往容器中添加对象
         */
        void put(String thirdType, IThirdLoginHandler bean) {
            beanMap.put(thirdType, bean);
        }

        /**
         * 从容器中获取对象
         */
        IThirdLoginHandler get(String thirdType) {
            IThirdLoginHandler bean = beanMap.get(thirdType);
            if (bean == null) {
                throw new BaseException(ServerCode.NOT_FOUND);
            }
            return bean;
        }


    }

    public IThirdLoginHandler getHandler(String thirdType) {
        return container.get(thirdType);
    }

}
